package com.gitee.swsk33.singleinstance;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 单例容器
 */
public class SingleContainer {

	private SingleContainer() {
	}

	// 存放所有单例的容器，键为类的全限定名，值为对应单实例
	private static Map<String, Object> container = new ConcurrentHashMap<>();

	/**
	 * 获取对应类的单实例，不存在则创建
	 *
	 * @param className 类的全限定名
	 * @return 单实例
	 */
	public synchronized static Object getInstance(String className) throws Exception {
		if (!container.containsKey(className)) {
			Object instance = Class.forName(className).getConstructor().newInstance();
			container.put(className, instance);
			return instance;
		}
		return container.get(className);
	}

}